package com.xoa.service.party;


import com.xoa.dao.party.EnConstructionSiteMapper;
import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.model.party.EnConstructionSite;
import com.xoa.model.users.Users;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 在建工地
 * Created by gsb on 2018/1/6.
 */
@Service
public class EnConstructionSiteService {
    @Resource
    private EnConstructionSiteMapper enConstructionSiteMapper;
    @Resource
    private MapOwnerinfoMapper mapOwnerinfoMapper;
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 上午10:10:51
     * 类介绍  :   新建
     * 构造参数:
     *
     */
    public ToJson<EnConstructionSite> insertSelective(EnConstructionSite enConstructionSite, HttpServletRequest request, String gridLocation){
        ToJson<EnConstructionSite> json = new ToJson<>();
        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            if(gridLocation!=null){
                enConstructionSite.setNo1(gridLocation);
            }
            enConstructionSite.setCreateUser(user.getUserId());
            enConstructionSite.setCreateTime(DateFormat.getDatestr(new Date()));
            enConstructionSiteMapper.insertSelective(enConstructionSite);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 上午10:10:51
     * 类介绍  :   删除
     * 构造参数:
     *
     */
    public ToJson<EnConstructionSite> deleteByPrimaryKey(Integer sid){
        ToJson<EnConstructionSite> json = new ToJson<>();
        try {
            enConstructionSiteMapper.deleteByPrimaryKey(sid);
            json.setFlag(0);
            json.setMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
         *
         * 创建作者:   季佳伟
         * 创建日期:   2018-1-6 上午10:18:51
         * 类介绍  :   修改
         * 构造参数:
         *
         */
        public ToJson<EnConstructionSite> updateByPrimaryKeySelective(EnConstructionSite enConstructionSite, HttpServletRequest request, String gridLocation){
            ToJson<EnConstructionSite> json = new ToJson<>();
        try {
            if(gridLocation!=null){
                enConstructionSite.setNo1(gridLocation);
            }
            enConstructionSiteMapper.updateByPrimaryKeySelective(enConstructionSite);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 上午10:25:51
     * 类介绍  :   详情
     * 构造参数:
     *
     */
    public ToJson<EnConstructionSite> selectById(Integer sid){
        ToJson<EnConstructionSite> json = new ToJson<>();
        try {
            EnConstructionSite enConstructionSite = enConstructionSiteMapper.selectById(sid);
            json.setObject(enConstructionSite);
            json.setFlag(0);
            json.setMsg("成功");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 上午10:30:51
     * 类介绍  :   列表  或 导出 也可条件查询
     * 构造参数:
     *
     */
    public ToJson<EnConstructionSite> queryList(EnConstructionSite enConstructionSite, Integer page, Integer pageSize,
                                                boolean useFlag, HttpServletRequest request, HttpServletResponse response, String export){
        ToJson<EnConstructionSite> json = new ToJson<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            if(useFlag){
                map.put("page", pageParams);
            }
            map.put("enConstructionSite",enConstructionSite);
            if(export==null){
                export="0";
            }
            List<EnConstructionSite> enConstructionSiteList = enConstructionSiteMapper.queryList(map);
            if (enConstructionSiteList!=null&&enConstructionSiteList.size()>0){
                for (EnConstructionSite enConstructionSite1:enConstructionSiteList){
                    if ("1".equals(enConstructionSite1.getConstructionPermit())){
                        enConstructionSite1.setConstructionPermit("有");
                    }else if ("0".equals(enConstructionSite1.getConstructionPermit())){
                        enConstructionSite1.setConstructionPermit("无");
                    }else {
                        enConstructionSite1.setConstructionPermit("");
                    }
                    if("1".equals(enConstructionSite1.getProjectType())){
                        enConstructionSite1.setProjectType("房建");
                    }else if ("2".equals(enConstructionSite1.getProjectType())){
                        enConstructionSite1.setProjectType("拆除");
                    }else if ("3".equals(enConstructionSite1.getProjectType())){
                        enConstructionSite1.setProjectType("市政");
                    }else if ("4".equals(enConstructionSite1.getProjectType())){
                        enConstructionSite1.setProjectType("装修");
                    }else if ("5".equals(enConstructionSite1.getProjectType())){
                        enConstructionSite1.setProjectType("园林");
                    }else if ("6".equals(enConstructionSite1.getProjectType())){
                        enConstructionSite1.setProjectType("水务");
                    }else {
                        enConstructionSite1.setProjectType("");
                    }
                    if ("1".equals(enConstructionSite1.getConstructionProgress())){
                        enConstructionSite1.setConstructionProgress("基础土方施工");
                    }else if ("2".equals(enConstructionSite1.getConstructionProgress())){
                        enConstructionSite1.setConstructionProgress("主体建设施工");
                    }else if ("3".equals(enConstructionSite1.getConstructionProgress())){
                        enConstructionSite1.setConstructionProgress("市政配套施工");
                    }else if ("4".equals(enConstructionSite1.getConstructionProgress())){
                        enConstructionSite1.setConstructionProgress("完工");
                    }else {
                        enConstructionSite1.setConstructionProgress("");
                    }
                }
            }
            json.setObj(enConstructionSiteList);
            json.setTotleNum(enConstructionSiteMapper.selectCount(enConstructionSite));
            json.setMsg("ok");
            json.setFlag(0);
            if ("1".equals(export)){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("在建工地信息", 13);
                String[] secondTitles = {"工程名称", "建设工程地址","是否有施工许可证", "施工许可证号","工程类型",
                        "工程规模","开工日期","竣工日期","土方运输单位", "施工进度","负责人",
                        "联系电话","备注"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"projectName", "projectAddress","constructionPermit", "constructionLicense",
                        "projectType", "projectScale","beginTime","endTime","transportUnit", "constructionProgress",
                        "responsiblePerson",
                        "contactNum","note3"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, enConstructionSiteList, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "在建工地信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-5 下午16:25:51
     * 类介绍  :   导入
     * 构造参数:
     *
     */
    public ToJson<EnConstructionSite> importEnConstructionSite(MultipartFile file, HttpServletResponse response,
                                                               HttpServletRequest request, HttpSession session) {
        ToJson<EnConstructionSite> json = new ToJson<>();
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
            String fileName = file.getOriginalFilename();
            if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                int pos = fileName.indexOf(".");
                String extName = fileName.substring(pos);
                String newFileName = uuid + extName;
//                File dest = new File(path.toString(), newFileName);
//                file.transferTo(dest);
//                // 将文件上传成功后进行读取文件
//                // 进行读取的路径
//                String readPath = path.append(newFileName).toString();
                InputStream in =  file.getInputStream();
                HSSFWorkbook excelObj = new HSSFWorkbook(in);
                HSSFSheet sheetObj = excelObj.getSheetAt(0);
                Row row = sheetObj.getRow(0);
                int colNum = row.getPhysicalNumberOfCells();
                int lastRowNum = sheetObj.getLastRowNum();
                EnConstructionSite enConstructionSite = null;
                File dest = new File(path.toString(), newFileName);
                for (int i = 1; i <= lastRowNum; i++) {
                    enConstructionSite = new EnConstructionSite();
                    row = sheetObj.getRow(i);
                    String value = "";
                    if (row != null) {
                        for (int j = 0; j < colNum; j++) {
                            Cell cell = row.getCell(j);
                            if (cell != null) {
                                switch (j) {
                                    case 0:
                                        //工程名称
                                        enConstructionSite.setProjectName(cell.getStringCellValue());
                                        break;
                                    case 1:
                                        //建设工程地址
                                        enConstructionSite.setProjectAddress(cell.getStringCellValue());
                                        break;
                                    case 2:
                                        //是否有施工许可证
                                        if ("有".equals(cell.getStringCellValue().trim())){
                                            enConstructionSite.setConstructionPermit("1");
                                        }else {
                                            enConstructionSite.setConstructionPermit("0");
                                        }
                                        break;
                                    case 3:
                                        //施工许可证号
                                        if(cell.getCellType() == CellType.NUMERIC){
                                            cell.setCellType(CellType.STRING);
                                        }
                                        enConstructionSite.setConstructionLicense(cell.getStringCellValue());
                                        break;
                                    case 4:
                                        //工程类型
                                        if ("房建".equals(cell.getStringCellValue().trim())){
                                            enConstructionSite.setProjectType("1");
                                        }else if ("拆除".equals(cell.getStringCellValue().trim())){
                                            enConstructionSite.setProjectType("2");
                                        }else if ("市政".equals(cell.getStringCellValue().trim())){
                                            enConstructionSite.setProjectType("3");
                                        }else if ("装修".equals(cell.getStringCellValue().trim())){
                                            enConstructionSite.setProjectType("4");
                                        }else if ("园林".equals(cell.getStringCellValue().trim())){
                                            enConstructionSite.setProjectType("5");
                                        }else if ("水务".equals(cell.getStringCellValue().trim())){
                                            enConstructionSite.setProjectType("6");
                                        }else {
                                            enConstructionSite.setProjectType("");
                                        }
                                        break;
                                    case 5:
                                        //工程规模
                                        if(cell.getCellType() == CellType.NUMERIC){
                                            cell.setCellType(CellType.STRING);
                                        }
                                        enConstructionSite.setProjectScale(cell.getStringCellValue());
                                        break;
                                    case 6:
                                        //开工日期
                                        String result1 = null;
                                        if(cell.getCellType() == CellType.NUMERIC){
                                            short format = cell.getCellStyle().getDataFormat();
                                            SimpleDateFormat sdf = null;
                                            if(format == 14 || format == 31 || format == 57 || format == 58){
                                                //日期
                                                sdf = new SimpleDateFormat("yyyy-MM-dd");
                                            }else if (format == 20 || format == 32) {
                                                //时间
                                                sdf = new SimpleDateFormat("HH:mm");
                                            }
                                            double v = cell.getNumericCellValue();
                                            Date dates = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                            result1 = sdf.format(dates);
                                            enConstructionSite.setBeginTime(result1);
                                            break;
                                        }
                                        enConstructionSite.setBeginTime(cell.getStringCellValue());
                                        break;
                                    case 7:
                                        //竣工日期
                                        String result2 = null;
                                        if(cell.getCellType() == CellType.NUMERIC){
                                            short format = cell.getCellStyle().getDataFormat();
                                            SimpleDateFormat sdf = null;
                                            if(format == 14 || format == 31 || format == 57 || format == 58){
                                                //日期
                                                sdf = new SimpleDateFormat("yyyy-MM-dd");
                                            }else if (format == 20 || format == 32) {
                                                //时间
                                                sdf = new SimpleDateFormat("HH:mm");
                                            }
                                            double v = cell.getNumericCellValue();
                                            Date dates = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                            result2 = sdf.format(dates);
                                            enConstructionSite.setEndTime(result2);
                                            break;
                                        }
                                        enConstructionSite.setEndTime(cell.getStringCellValue());
                                        break;
                                    case 8:
                                        //土方运输单位
                                        enConstructionSite.setTransportUnit(cell.getStringCellValue());
                                        break;
                                    case 9:
                                        //施工进度
                                        if ("基础土方施工".equals(cell.getStringCellValue())){
                                            enConstructionSite.setConstructionProgress("1");
                                        }else if ("主体建设施工".equals(cell.getStringCellValue())){
                                            enConstructionSite.setConstructionProgress("2");
                                        }else if ("市政配套施工".equals(cell.getStringCellValue())){
                                            enConstructionSite.setConstructionProgress("3");
                                        }else if ("完工".equals(cell.getStringCellValue())){
                                            enConstructionSite.setConstructionProgress("4");
                                        }else {
                                            enConstructionSite.setConstructionProgress("");
                                        }
                                        break;
                                    case 10:
                                        //负责人
                                        enConstructionSite.setResponsiblePerson(cell.getStringCellValue());
                                        break;
                                    case 11:
                                        //联系电话
                                        if(cell.getCellType() == CellType.NUMERIC){
                                            cell.setCellType(CellType.STRING);
                                        }
                                        enConstructionSite.setContactNum(cell.getStringCellValue());
                                        break;
                                    case 12:
                                        //备注
                                        enConstructionSite.setNote3(cell.getStringCellValue());
                                        break;
                                    case 13:
                                        enConstructionSite.setNo1(mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue()));
                                        break;
                                    default:
                                        json.setFlag(0);
                                        json.setMsg("err");
                                        break;
                                }
                            }

                        }
                        enConstructionSite.setCreateUser(users.getUserId());
                        enConstructionSite.setCreateTime(DateFormat.getCurrentTime());
                        //将数据放入数据库
                        int count=enConstructionSiteMapper.insertSelective(enConstructionSite);
                        if(count>0) {
                            successCount = successCount + count;
                        }
                        dest.delete();
                    }
                }

            }
        }
        if(successCount>0){
            json.setTotleNum(successCount);
            json.setMsg("ok");
            json.setFlag(0);
            return  json;
        }
        }catch (Exception e){
            e.printStackTrace();
            json.setTotleNum(successCount+1);
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;

    }
    }
